<style>
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
<template>
  <div>
  	<Card class="mb-10">
    	<Row>
    		<Col span="12">
    			<h3>医生管理</h3>
    		</Col>
    		<Col span="12" class="text-right">
          <component2 v-if="Super">
            <Button type="primary" @click='addItem'class="mr-10">新建</Button>
          </component2>
				  <component2 v-if="Super">
            <Button type="error" @click="myDelete">删除</Button>
          </component2>
    		</Col>
    	</Row>
  	</Card>
    <Card>
		<Row style="margin-bottom: 10px;">
          <span>创建  日期范围：</span>
          <DatePicker style="width:160px" type="date" format="yyyy-MM-dd " :value='createTimeMin' @on-change='myStartTime' placeholder="开始日期"></DatePicker>
          <span>~</span>
          <DatePicker   style="width:160px;margin-right:20px;" type="date" format="yyyy-MM-dd " :value='createTimeMax' @on-change='myEndTime' placeholder="结束日期"></DatePicker>
          <span>关键字：</span>
          <Input placeholder="请输入要搜索的姓名" v-model.trim='searchText' style="width:200px;margin-right:20px;"></Input>
          <Button type="primary" @click='search'>搜索</Button>
		</Row>
        <Table size="large" @on-selection-change="selectOption" stripe ref="selection" :columns="tableCol" :data="tableData">
        </Table>
        <Page class='mt-10 text-right' :total="total" :current='currentPage' :page-size='pageSize' @on-change="changePage" @on-page-size-change="changeSize" show-sizer show-total/>
    </Card>
    <Modal
      v-model="saveItem"
      :title="itemTitle"
      @on-cancel='closeSaveItem'>
      <Form ref="formData" :model="formData" :label-width="80">
        <input type="hidden" name='id' v-model="formData.id">
          <input type="hidden" name='imgUrl' v-model="formData.imgUrl">
        <FormItem label="姓名"  >
            <Input v-model="formData.name" placeholder="请输入要添加的医生姓名" :maxlength="15"></Input>
        </FormItem>
          <FormItem label="性别" >
            <RadioGroup v-model="formData.sex">
                <Radio :label="1">男</Radio>
                <Radio :label="2">女</Radio>
            </RadioGroup>
        </FormItem>
          <FormItem label="手机号" >
             <Input v-model="formData.phone" placeholder="请输入手机号" :maxlength="11"></Input>
        </FormItem>
          <FormItem label="邮箱">
             <Input v-model="formData.email" placeholder="请输入邮箱" :maxlength="20"></Input>
        </FormItem>
          <component2 v-if="Super">
          <FormItem label="请选择类型" >
             <Row>
                <Col span="24" style="padding-right:10px">
                    <Select v-model="formData.doctorCategoryid" filterable>type
                        <Option v-for="item in courseList" :value="item.id" :key="item.id">{{ item.type }}</Option>
                    </Select>
                </Col>
            </Row>
        </FormItem>      
        <FormItem label="图片上传">
        <template>
          <div>
            <div class="imageWrap">
              <img :src="insideSrc"  alt="" width="50%" height="20%" >
            </div>
            <Upload
              action="/api/doctor/uploadImg"
              :on-success="handleUploadSuccess"
              :accept="acceptFile"
              name="name"
              :before-upload="beforeUpload">
              <Button style="width: 150px;" type="primary">上传图片</Button>
            </Upload>
          </div>
        </template>
        </FormItem>
        </component2> 
      </Form>
      <div slot="footer">
          <Button type="default"  @click="closeSaveItem">关闭</Button>
          <Button type="primary" :disabled='saveItemStatu'  @click="saveItemOk">确认</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { hasOneOf } from '@/libs/tools'
import { doctorTableData,updateDoctor, commentDels,addDoctor,getAllCategory} from '@/api/data'
export default {
  data () {
    return {
      sideImg:'',
      insideSrc:'',
      acceptFile: 'image/png,image/jpeg',
      createTimeMin:'',
      createTimeMax:'',
    	searchText: '',	// 搜索内容初始化
      pageSize:10,
      currentPage:1,
      total:1,
      formData:{},     //表单信息
      addUser:true,   //是否为新增用户
    	upLoadPic: true,		// 照片上传模态框
      picture:[],          //照片上传
      computerId:0,        //照片上传参数
      saveItem:false,     //保存操作框
      saveItemStatu:false,     //保存点击状态
      itemTitle:'新建电脑',   //保存操作框title
      selectItemArr: [],		// 选中项目id
     tableCol: [
      {
        type: 'selection',
        width: 60,
        align: 'center'
      },
      {
        title: '姓名',
        key: 'name'
      },
      {
        title: '创建日期',
        key: 'createTime'
      },
      {
        title: '性别',
        key: 'sex' ,
        render: (h, params) => {
             if (params.row.sex===1){ return h('span','男') };
              if (params.row.sex===2){ return h('span','女')};
        }
      },
      {
        title: '手机号',
        key: 'phone'
      },
      {
        title: '邮箱',
        key: 'email',
      },
       {
          title: '类型',
          key: 'doctorCategory',
          render: (h, params) => {
            var oName = params.row.doctorCategory;
            return h('div', [
              h('span', {}, oName.type)
            ])
          }
        },
         {
          title: '图片',
            key: 'imgUrl',  
             render: (h, params) => {
            return h('div', [
              h('img', {
                style: {
                  width: '80px',
                  height: '50px',
                  borderRadius: '4px'
                },
                attrs: {
                  src: "http://"+params.row.imgUrl// 如果是1那种写法,不能实时获取,获取的还是undefined
                }
              })
            ])
          }
         },
        {
          width:100,
          title: '操作',
          key: 'examineStatus',
          checkAccess: ['superAdmin'],
          render: (h, params) => {
            console.log()
            return h('div', [
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'large',
                  disabled:this.viewAccessComputer
                },
                     on: {
                  click: () => {
                    let getData = JSON.parse(JSON.stringify(this.tableData[params.index]));
                    this.formData = getData;
                    this.itemTitle = '编辑医生';
                    this.insideSrc="http://"+params.row.imgUrl;   
                    this.addUser = false;
                    this.saveItem = true;
                    getAllCategory().then(res => {
                      if(res.data.success){
                         this.courseList = res.data.result.data; 
                      //this.classList = res.data.result.courses;
                        console.log(JSON.stringify("+++"+ this.courseList))
                        console.log("编辑数据"+this.formData.imgUrl)
                      }else{
                          this.$Message.warning({
                            content:res.data.errorMsg
                          })
                        }
                      })
                  }
                }
              }, '编辑')
            ])
          },

        }
      ],
      tableData: [],
      // 图片上传
        coverLink :'',
        show : true,
        visible: false,
        header:{
          'token': sessionStorage.getItem('token')
        },
      imgName: '',
      targetKeys: [],
      courseList:[],
      listStyle: {
          width: '150px',
          height: '200px'
      }
    }
  },
  methods: {
    async pageInit(){
      doctorTableData(this.pageSize,this.currentPage,this.createTimeMin,this.createTimeMax,this.searchText).then(res => {
        if(res.data.success){
          this.total = res.data.result.data.totalSize;
          this.tableData = res.data.result.data.pageList;
        }else if(res.data.errorMsg){
          this.$Message.warning({
            content:res.data.errorMsg
          })
        }
      })
    },
    changePage(page){
      this.currentPage = page;
      this.pageInit();
    },
    changeSize(size){   
      this.pageSize = size;
      this.currentPage = 1;
      this.pageInit();
    },
 beforeUpload (file) {
    
     if (!this.acceptFile.split(',').includes(file.type)) {
        this.$Message.warning('未选中图片格式的文件')
        return false
      }
      if (file.size / 1024 > this.maxSize) {
        this.$Message.warning(`文件大小超过了${this.maxSize}KB`)
        return false
      }
       // 转换为base64
 
      const reader = new FileReader()
      // 将读取到的文件编码成Data URL
      reader.readAsDataURL(file)
      reader.onload = (event) => {
      this.insideSrc = event.srcElement.result
      }
      // 若返回 false 则停止上传,此时中断则判断大小无法使用max-size属性判断
      return true
  },
  handleUploadSuccess (res, file) {
        this.sideImg = res.result.url;
        console.log('IMG数据'+this.sideImg)
        return sideImg
    },
    addItem(){
      var sideImg=this.sideImg;
      this.formData = {};
      this.itemTitle = '添加医生';
      this.insideSrc=sideImg,
      this.addUser = true;
      this.saveItem = true;
      getAllCategory().then(res => {
        if(res.data.success){
            this.courseList =res.data.result.data; 
          console.log(JSON.stringify("+++"+ this.courseList))
        }else{
            this.$Message.warning({
              content:res.data.errorMsg
            })
          }
        })
    },
    closeUpload(){
      alert(1);
      this.upLoadPic = false;
      this.defaultList=[];
      this.uploadList=[];
    },
    // 关闭保存项目模态框
    closeSaveItem(){
      this.formData = {};
      this.saveItem = false;
      this.targetKeys=[];
    },
    saveItemOk(){
      var that = this;
      var formData = this.formData;
      var sideImg=this.sideImg;
      this.formData.imgUrl=sideImg;
      console.log(JSON.stringify('阿萨德'+sideImg))
      if(!formData.name){
        this.$Message.warning({
          content:'请填写您的姓名！'
        });
        return;
      }else if (!/[\u4e00-\u9fa5_a-zA-Z]+$/.test(formData.name)){
        this.$Message.warning({
          content:'请填写正确的姓名'
        });
        return;
      };
      if(!formData.phone){
        this.$Message.warning({
          content:'请填写您的手机号'
        });
        return;
      }else if (!/^1(3|4|5|6|7|8)\d{9}$/.test(formData.phone)){
        this.$Message.warning({
          content:'请填写正确的手机号'
        });
        return;
      };
       if(!formData.email){
        this.$Message.warning({
          content:'请填写您的邮箱！'
        });
        return;
      }else if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(formData.email)){
        this.$Message.warning({
          content:'请填写正确的邮箱地址'
        });
        return;
      };
       if(!formData.sex){
        this.$Message.warning({
          content:'请选择您的性别！'
        });
        return;}
        if(this.addUser){
        addDoctor(this.formData,this.targetKeys).then(res => {
          // console.log(JSON.stringify(res))
          if(res.data.result && res.data.result.error){
            this.$Message.warning({
              content:res.data.result.error
            })
            return;
          }else if(res.data.success){
            this.$Message.success({
              content:'保存用户成功'
            });
            that.saveItem = false;
            that.pageInit();
          }else if(res.data.errorMsg){
            this.$Message.warning({
              content:res.data.errorMsg
            })
          }
          that.saveItemStatu = false;
        })
      }else{
        this.saveItemStatu = true;
        updateDoctor(this.formData).then(res => {
          // var that = this;
          that.saveItemStatu = false;
          if(res.data.success){
           this.$Message.success({
              content:'修改用户成功'
            });
            that.saveItem = false;
            that.pageInit();
          }else if(res.data.errorMsg){
            this.$Message.warning({
              content:res.data.errorMsg
            })
          }
        })
      }
    },
  	// 选中项
  	selectOption (selection, row) {
  		this.selectItemArr = []
  		for (let item of selection) {
        this.selectItemArr.push(item.id)
	    }
  	},
  	// 删除
  	myDelete () {
  		var selectItemArr = this.selectItemArr
      if(selectItemArr.length<1){
        this.$Message.warning({
          content:'请选择项目！'
        })
        return;
      }
      commentDels('/doctor/deleteDoctorByIds', selectItemArr).then(res => {
        console.log(JSON.stringify(res))
        if(res.data.success){
          this.selectItemArr=[];
          this.pageInit();
          this.$Message.success({
            content:'删除成功！'
          });
        }else if(res.data.errorMsg){
          this.$Message.warning({
            content:res.data.errorMsg
          })
        }

        // this.tableData = res.data.result.data.pageList;
      })
      },
  	// 开始日期
  	myStartTime (newTime) {
  		this.createTimeMin = newTime
  	},
  	// 结束日期
  	myEndTime (newTime) {
  		this.createTimeMax = newTime
    },
  	birthdayTime (newTime) {
  		this.formData.birthday = newTime
    },
  	// 搜索
  	search () {
      this.currentPage = 1;
  		this.pageInit();
  	},
    handleChange(newTargetKeys) {
        this.targetKeys = newTargetKeys;
    },
    render (item) {
        return item.label;
    },
    reloadMockData () {
        this.transfer = this.getMockData();
        this.targetKeys = this.getTargetKeys();
    }

  },
  mounted () {
    // 初始化
    doctorTableData(10, 1).then(res => {
       console.log("----"+JSON.stringify(res));
      if(res.data.success){
        this.total = res.data.result.data.totalSize;
        this.tableData = res.data.result.data.pageList;
      }else if(res.data.errorMsg){
        this.$Message.warning({
          content:res.data.errorMsg
        })
      }
    })
    // 图片上传
    this.uploadList = this.$refs.upload.fileList;
  },
  computed: { 
    access () {
      return this.$store.state.user.access
    },
    //所有权限
    viewAccessAll () {
      return hasOneOf(['superAdmin', 'computer','student'], this.access)
    },
    //部分权限
    viewAccessComputer () {
      return hasOneOf(['computer','student'], this.access)
    },
    Super () {
      return hasOneOf(['superAdmin'], this.access)
    }
  }
}
</script>

